/*
 * alocxx.cpp
 *
 * Copyright (c) 2009, Eugen Stoian <stoian.e@gmail.com>
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 3 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 * http://www.fsf.org/licensing/licenses/lgpl.txt
 */
#include "memalloc.h"
#include <cstdint>
namespace pxx {

/*!
 * \fn memalloc(size_t size)
 * \brief Allocates 16 byte aligned memory .
 *
 * Memory must be freed using pxx::memfree() .
 */
void* memalloc(size_t size){

	char *ptr, *ptr2, *aligned_ptr;

	uintptr_t align_size = 16;
	uintptr_t align_mask = 15;

	ptr = (char *) malloc(size + align_size + sizeof(uintptr_t));

	if (ptr == NULL)
		return (NULL);

	ptr2 = ptr + sizeof(uintptr_t);
	aligned_ptr = ptr2 + (align_size - ((size_t) ptr2 & align_mask));
	ptr2 = aligned_ptr - sizeof(uintptr_t);
	*((uintptr_t *) ptr2) = (uintptr_t)(aligned_ptr - ptr);
	return (aligned_ptr);
}
/*!
 * \fn memfree(void* ptr)
 * \brief Frees memory previously allocated with pxx::memalloc();
 */
void  memfree(void* ptr){
	uintptr_t *ptr2 = (uintptr_t *) ptr - 1;
	ptr = (char*)ptr - *ptr2;
	free(ptr);
}
}
